import org.jsecurity.crypto.hash.Sha1Hash
class UserController {
    
    // the delete, save and update actions only accept POST requests
    def allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def index = {
        if(!params.max) params.max = 10
        [ users: User.list( params ) ]
    }

    def show = {
        def user = User.get( params.id )

        if(!user) {
            flash.message = "User not found with id ${params.id}"
            redirect(action:index)
        }
        else { return [ user : user ] }
    }

    def delete = {
        def user = User.get( params.id )
        if(user) {
        	user.delete()
            flash.message = "User ${params.id} deleted"
            redirect(action:index)
        }
        else {
            flash.message = "User not found with id ${params.id}"
            redirect(action:index)
        }
    }

    def edit = {
        def user = User.get( params.id )

        if(!user) {
            flash.message = "User not found with id ${params.id}"
            redirect(action:index)
        }
        else {
            return [ user : user ]
        }
    }

    def update = { FormCommand cmd ->
        def user = User.get( params.id )
        if(user && !cmd.hasErrors()) {
        	user.properties = params
        	user.passwordHash =  new Sha1Hash(cmd.password).toHex()
            if(!user.hasErrors() && user.save()) {
                flash.message = "User ${params.id} updated"
                redirect(action:show,id:user.id)
            }
            else {
                render(view:'edit',model:[user:user,cmd:cmd])
            }
        }
        else {
            flash.message = "User not found with id ${params.id}"
            redirect(action:edit,id:params.id)
        }
    }

    def create = {
        def user = new User()
        user.properties = params
        return ['user':user]
    }

    def save = { FormCommand cmd ->
    	def user = new User()
    	bindData(user,cmd)
	    if(cmd.hasErrors()){
	        render(view:'create',model:[cmd:cmd, user:user])
		} else {
	        user.passwordHash =  new Sha1Hash(cmd.password).toHex()
	        if(!user.hasErrors() && user.save()) {
	            flash.message = "User ${user.id} created"
	            redirect(controller:'new',action:create,id:user.id)
	        }
	        else {
	            render(view:'create',model:[user:user])
	        }
    	}
    }
}

class FormCommand{
	String password
	String repassword
	String username
	String email
	
	static constraints = {
		password(blank:false,validator: {
			var,obj->
			var==obj.repassword
			}
		)
    }
}
